import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Link } from 'dva/router';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Table,
  Tooltip,
  Popconfirm,
} from 'antd';
import {
  ChartCard,
  yuan,
  MiniArea,
  MiniBar,
  MiniProgress,
  Field,
  Bar,
  Pie,
  TimelineChart,
} from 'components/Charts';
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import styles from './DiscountList.less';

const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
    //0未开始，1进行中，2已结束
const statusMap = [  'success','processing','default'];
const status = ['未开始', '运行中', '已结束'];


const CreateForm = Form.create()(props => {
  const { modalVisible, form, handleAdd, handleModalVisible } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      handleAdd(fieldsValue);
    });
  };
  return (
    <Modal
      title="新建规则"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
    >
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="描述">
        {form.getFieldDecorator('desc', {
          rules: [{ required: true, message: 'Please input some description...' }],
        })(<Input placeholder="请输入" />)}
      </FormItem>
    </Modal>
  );
});

@connect(({ coupon, loading }) => ({
  coupon,
  loading: loading.models.rule,
}))
@Form.create()
export default class TableList extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    dataDetail : {} , //单独数据详情，用于数据展示
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'coupon/fetch',
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      startIndex: (pagination.current - 1)* pagination.pageSize,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'coupon/fetch',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'coupon/fetch',
      payload: {},
    });
  };

  toggleForm = () => {
    this.setState({
      expandForm: !this.state.expandForm,
    });
  };

  handleMenuClick = e => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;

    if (!selectedRows) return;

    switch (e.key) {
      case 'remove':
        dispatch({
          type: 'coupon/remove',
          payload: {
            no: selectedRows.map(row => row.no).join(','),
          },
          callback: () => {
            this.setState({
              selectedRows: [],
            });
          },
        });
        break;
      default:
        break;
    }
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'coupon/fetch',
        payload: values,
      });
    });
  };

  handleModalVisible = (flag, data) => {
    if(flag){
      this.props.dispatch({
        type : 'coupon/fetchGoods',
        payload : {
          id : data.id
        }
      });
      this.setState({
        dataDetail : data
      });
    }
    this.setState({
      modalVisible: !!flag,
    });
  };

  handleAdd = fields => {
    this.props.dispatch({
      type: 'coupon/add',
      payload: {
        description: fields.desc,
      },
    });

    message.success('添加成功');
    this.setState({
      modalVisible: false,
    });
  };

  renderSimpleForm() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="优惠券名称">
              {getFieldDecorator('title')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="状态">
              {getFieldDecorator('status')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value="0">未开始</Option>
                  <Option value="1">进行中</Option>
                  <Option value="2">已结束</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }
  bindChangeStatus = (id)=>{
    this.props.dispatch({
      type : 'coupon/changeStatus',
      payload : {
        id : id
      }
    });
  }

  bindDelete = (id)=>{
    this.props.dispatch({
      type : 'coupon/deleteItem',
      payload : {
        id : id
      }
    });
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const topColResponsiveProps = {
      xs: 24,
      sm: 12,
      md: 12,
      lg: 12,
      xl: 8,
      style: { marginBottom: 24 },
    };
    const { coupon: { data, dataGoods }, loading } = this.props;
    const { selectedRows, modalVisible, dataDetail } = this.state;

    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
    };

    const columns = [
      {
        title: '优惠券名称',
        dataIndex: 'title',
      },
      {
        title: '有效时间',
        render: (text ,record) => {
          switch(record.rule.licence.type){
            case 2 :
              return <span>{`${record.rule.licence.value}`}</span>
              break;
            case 0 :
              return <span>{`领券后当日起${record.rule.licence.value}天内有效`}</span>
              break;
            case 1:
              return <span>{`领券后次日起${record.rule.licence.value}天内家效`}</span>
              break;
            default:
              break;
          }
        }
      },
      {
        title: '活动标签',
        dataIndex: 'tag',
      },
      {
        title: '领取限制',
        dataIndex: 'rule.limit',
      },
      {
        title: '总张数 / 已领取',
        dataIndex: 'total',
        render : (val, record)=>{
          return <span>{val}/{record.total - record.rest}</span>
        }
      },
      {
        title: '剩余',
        dataIndex : 'rest',
      },
      {
        title: '已使用',
        dataIndex : 'totalOrder'
      },
      {
        title: '使用率 / 领取率',
        dataIndex : 'useRate',
        render : (val, record)=>{
          return <span>{val}/{record.gotRate}</span>
        }
      },
      {
        title : '状态',
        dataIndex : 'status',
        render : (val, record)=>{
          return <Badge status={statusMap[val]} text={status[val]} />;
        }
      },
      {
        title: '操作',
        render: (text, record) => (
          <Fragment>
            <a href="javascript:;" onClick={()=>{this.handleModalVisible(true,record)}}>数据</a>
            <Divider type="vertical" />
            <Popconfirm title="你确定要提前结束？" okText="确定" cancelText="取消" onConfirm={()=>{ this.bindChangeStatus(record.id) }}>
            <a href="#">结束</a>
            </Popconfirm>
            <Divider type="vertical" />
            <Popconfirm title="你确定删除？" okText="确定" cancelText="取消" onConfirm={()=>{ this.bindDelete(record.id) }}>
            <a href="">删除</a>
            </Popconfirm>
            <Divider type="vertical" />
            <Link to={`/sales/coupon-add?id=${record.id}`}>修改</Link>
          </Fragment>
        ),
      },
    ];

    return (
      <div>
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>

              <Button>
                <Link to={`/sales/coupon-add`}>新建</Link>
              </Button>
              {selectedRows.length > 0 && (
                <span>
                  <Button>删除</Button>
                </span>
              )}
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
              rowSelection= {null}
            />
          </div>
        </Card>
        <Modal
          title="促销数据"
          width={900}
          visible={modalVisible}
          onOk={this.handleModalVisible}
          onCancel={()=>{this.handleModalVisible(false)}}
        >
          <p>优惠券名称：{dataDetail.title}</p>
          <Row gutter={24}>
            <Col {...topColResponsiveProps}>
              <ChartCard
                bordered={true}
                title="用券成交总金额"
                action={
                  <Tooltip title="使用该优惠券的订单付款总金额">
                    <Icon type="info-circle-o" />
                  </Tooltip>
                }
                total={dataDetail.totalPrice}
                contentHeight={46}
              >
              </ChartCard>
            </Col>
            <Col {...topColResponsiveProps}>
              <ChartCard
                bordered={true}
                title="优惠总金额"
                action={
                  <Tooltip title="使用该优惠券优惠的总金额">
                    <Icon type="info-circle-o" />
                  </Tooltip>
                }
                total={dataDetail.totalDiscount}
                contentHeight={46}
              >
              </ChartCard>
            </Col>
            <Col {...topColResponsiveProps}>
              <ChartCard
                bordered={true}
                title="费效比"
                action={
                  <Tooltip title="优惠总金额 / 用券总成交额">
                    <Icon type="info-circle-o" />
                  </Tooltip>
                }
                total={dataDetail.priceRate}
                contentHeight={46}
              >
              </ChartCard>
            </Col>
            <Col {...topColResponsiveProps}>
              <ChartCard
                bordered={true}
                title="用券比单价"
                action={
                  <Tooltip title="用券总成交额/使用该优惠券的付款订单数">
                    <Icon type="info-circle-o" />
                  </Tooltip>
                }
                total={dataDetail.couponPriceRate}
                contentHeight={46}
              >
              </ChartCard>
            </Col>
            <Col {...topColResponsiveProps}>
              <ChartCard
                bordered={true}
                title="新成交客户数"
                action={
                  <Tooltip title="使用该优惠券的新成交客户数">
                    <Icon type="info-circle-o" />
                  </Tooltip>
                }
                total={dataDetail.totalNewUser}
                contentHeight={46}
              >
              </ChartCard>
            </Col>
            <Col {...topColResponsiveProps}>
              <ChartCard
                bordered={true}
                title="老成交客户数"
                action={
                  <Tooltip title="使用该优惠券的老成交客户数">
                    <Icon type="info-circle-o" />
                  </Tooltip>
                }
                total={dataDetail.totalOldUser}
                contentHeight={46}
              >
              </ChartCard>
            </Col>
          </Row>
          <Table
            style={{marginTop: '8px'}}
            columns={[
              {
                title: '图片',
                dataIndex: 'img',
                render : (text)=>{
                  return <img src={text} width={50}  />
                }
              },
              {
                title: '名称',
                dataIndex: 'name'
              },
              {
                title: '单价',
                dataIndex : "unitPrice"
              },
              {
                title: '付款件数',
                dataIndex : "count"
              },
              {
                title: '付款金额',
                dataIndex : "totalPrice"
              }
            ]}
            dataSource={dataGoods}
          ></Table>
        </Modal>
      </div>
    );
  }
}
